<template>
  <div class="contain">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ Login.LoginType ? "登录" : "注册" }}</span>
          <el-button class="button" @click="ChangeType" text>{{
            Login.LoginType ? "注册" : "登录"
          }}</el-button>
        </div>
      </template>
      <el-form
        ref="LoginRef"
        status-icon
        :rules="rules"
        label-width="100px"
        :model="Login"
        style="max-width: 460px"
      >
        <el-form-item label="昵称" prop="userName" v-show="signShow">
          <el-input v-model="Login.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="Login.userEmail" />
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="Login.passWord" type="password" show-password />
        </el-form-item>
        <el-form-item class="code" label="验证码" v-show="signShow" prop="code">
          <el-input v-model="Login.code" />
          <el-button
            v-model="SendButton"
            :disabled="SendButton.buttonDisable"
            @click="sendMail(LoginRef)"
            type="primary"
            >{{ SendButton.buttonName }}</el-button
          >
        </el-form-item>
        <el-form-item class="b-login-item">
          <el-button
            :loading="isLoading"
            class="b-login"
            type="primary"
            @click="LoginUser(LoginRef)"
            round
          >
            {{ Login.LoginType ? "登录" : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.contain {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../assets//Login//bk1.jpg");

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 20px;
  }

  .box-card {
    width: 350px;
  }
}

.el-form-item {
  width: 90%;
  justify-content: center;
  margin-bottom: 30px;

  :deep .el-form-item__label {
    justify-content: center !important;
  }
}

.b-login {
  text-align: center;
  width: 100%;
}

.b-login-item {
  display: flex;
  width: 85%;
  margin: auto;

  :deep .el-form-item__content {
    margin-left: 0px !important;
  }
}

.code {
  :deep .el-input {
    width: 70%;
  }

  :deep .el-button {
    width: 30%;
  }
}
</style>

<script setup>
import { reactive, ref, inject, h } from "vue";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
const store = useStore();
//首先在setup中定义
const router = useRouter();

const axios = inject("axios", "");

//是否显示验证码和昵称框
const signShow = ref(false);
//表单校验状态
const LoginRef = ref();

//邮箱|密码|验证码
const Login = reactive({
  userName: "",
  userEmail: "",
  passWord: "",
  code: "",
  LoginType: true,
});
//邮箱校验规则
const emailVerify = (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (value === "") {
    callback(new Error("请输入邮箱"));
  } else if (emailRegex.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确邮箱"));
  }
};
//密码校验规则
const passVerify = (rule, value, callback) => {
  const passwordRegex = /^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]{8,}$/;
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (passwordRegex.test(value)) {
    callback();
  } else {
    callback(new Error("必须只能包含英文数字且至少8位"));
  }
};
//校验规则列表
const rules = {
  userEmail: [{ validator: emailVerify, trigger: "blur" }],
  passWord: [{ validator: passVerify, trigger: "blur" }],
  code: [{ required: true, message: "必填", trigger: "blur" }],
  userName: [{ required: true, message: "必填", trigger: "blur" }],
};

//切换登录注册
function ChangeType() {
  if (Login.LoginType) {
    Login.LoginType = false;
    signShow.value = true;
  } else {
    Login.LoginType = true;
    signShow.value = false;
  }
}

//发送邮箱按钮
const SendButton = reactive({
  buttonName: "发送",
  buttonDisable: false,
  num: 0,
});

//发送邮箱按钮5秒发送一次
function sendMail(LoginRef) {
  //先校验邮箱是否输入
  LoginRef.validateField("userEmail", (valid, fields) => {
    if (valid) {
      //发送请求
      var params = {
        email: Login.userEmail,
      };
      axios.get("BBS_VerificationCodes/GetEmailCode", null, params, (res) => {
        console.log(res);
      });
      //发送一次间隔5秒
      SendButton.buttonDisable = true;
      SendButton.num = 5;
      SendButton.buttonName = SendButton.num + "s";
      //倒计时
      const countDown = setInterval(() => {
        SendButton.num--;
        SendButton.buttonName = `${SendButton.num}s`;
        if (SendButton.num === 0) {
          clearInterval(countDown);
          SendButton.buttonDisable = false;
          SendButton.buttonName = "发送";
        }
      }, 1000);
    } else {
      console.log("邮箱未输入");
      return;
    }
  });
}
const UserInfo = reactive([]);
//登录or注册按钮
const isLoading = ref(false);
function LoginUser(LoginRef) {
  //登录,只校验邮箱和密码
  if (Login.LoginType) {
    LoginRef.validateField("userEmail", (valid, fields) => {
      if (valid) {
        LoginRef.validateField("passWord", (valid, fields) => {
          if (valid) {
            var data = {
              Password: Login.passWord,
              Email: Login.userEmail,
            };
            isLoading.value = true;
            axios.post("BBS_User/LogIn", data, null, (res) => {
              if (res.state == 200) {
                var data = JSON.parse(res.data);
                //token保存本地。其余信息保存session
                // store.commit(
                //   "loginPage/upUserInfo",
                //   {
                //     userName: data.userName,
                //     userEmail: data.userEmail,
                //     userId: data.userId,
                //     AvatarUrl: data.Avatar,
                //   }
                // );

                // store.commit("loginPage/upUserName", data.userName);
                // store.commit("loginPage/upUserEmail", data.userEmail);
                // store.commit("loginPage/upUserId", data.userId);
                // store.commit("loginPage/upUserAvatar", data.Avatar);
                sessionStorage.setItem("userName", data.userName);
                sessionStorage.setItem("userEmail", data.userEmail);
                sessionStorage.setItem("userId", data.userId);
                sessionStorage.setItem("AvatarUrl",data.Avatar)
                localStorage.setItem("Token", data.token);
                router.push(`/Home`);
              }
              isLoading.value = false;
              ElNotification({
                title: "提示",
                message: h("i", { style: "color: teal" }, res.message),
                duration: 1000,
              });
            });
          } else {
            ElNotification({
              title: "拒绝登录",
              message: h("i", { style: "color: teal" }, "请填写正确信息"),
              duration: 1000,
            });
            return;
          }
        });
      } else {
        return;
      }
    });
  } else {
    //注册，校验全部的表单
    LoginRef.validate((valid, fields) => {
      if (valid) {
        var data = {
          UserName: Login.userName,
          Password: Login.passWord,
          Email: Login.userEmail,
          AuthCode: Login.code,
        };
        isLoading.value = true;
        axios.post("BBS_User/SignIn", data, null, (res) => {
          //注册请求成功通知弹窗
          ElNotification({
            title: "提示",
            message: h("i", { style: "color: teal" }, res.message),
            duration: 1000,
          });
          if (res.state == 200) {
            ChangeType();
          } else {
            alert(res.message);
          }
        });
        isLoading.value = false;
      } else {
        //注册校验未通过通知弹窗
        ElNotification({
          title: "拒绝注册",
          message: h("i", { style: "color: teal" }, "请填写正确信息"),
          duration: 1000,
        });
      }
    });
  }
}
</script>
